<?php


namespace App\Api\Controllers;


use App\Models\BaseModel;
use App\Models\Cart;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\OrderRefund;
use App\Models\OrderTip;
use App\Models\Product;
use App\Models\ProductComment;
use App\Models\ProductSku;
use App\Models\UserAddress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Exception;

class OrderController extends Controller
{
    //订单提交检查
    public function orderCheck(Request $request)
    {
        if (empty($request->cart_id)) {
            return $this->responseFailed('cart_id必传');
        }
        $card_id = json_decode($request->cart_id);
        if (!is_array($card_id)) {
            return $this->responseFailed('card_id参数错误');
        }
        $user = auth()->user();
        $data = Cart::where('user_id',$user['id'])
            ->whereIn('id',$card_id)
            ->orderBy('id','desc')
            ->get()
            ->toArray();
        if (empty($data)) {
            return $this->responseFailed('购买商品不能为空');
        }
        $total_price = 0;
        foreach($data as &$val){
            $sku = ProductSku::find($val['product_sku_id']);
            if ($sku) {
                $price = $user['is_proxy']?$sku['vip_price']:$sku['price'];
                $total_price += $price * $val['amount'];
                $sku = $sku->toArray();
            }
            $val['sku'] = $sku;
            $val['product'] = Product::getProduct($val['product_id']);
        }
        $list = [];
        $list['total_price'] = $total_price;
        $list['is_proxy'] = $user['is_proxy'];
        if ($user) {
            $list['user'] = $user->toArray();
            $list['address'] = UserAddress::getDefault($user['id']);
        }
        $list['list'] = $data;
        //根据选择的地址计算运费
        return $this->responseData($list);
    }

    //快递费计算
    public function postFee(Request $request)
    {
        $input = $request->only([
            'address_id',
            'cart_id',
        ]);

        $validator = Validator::make($input, [
            'address_id' => 'required',
            'cart_id' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->responseFailed($validator->errors()->first());
        }
        try{
            $fee = Order::postfee($input['address_id'],$input['cart_id']);
            $data = [
                'fee' => $fee
            ];
            return $this->responseData($data);
        }catch (\Exception $e){
            return $this->responseFailed($e->getMessage());
        }
    }

    //创建订单
    public function add(Request $request)
    {
        $user = auth()->user();
        if (!$user) {
            return $this->responseFailed('token过期');
        }
        $input = $request->only([
            'address_id',
            'remark',
            'cart_id',
        ]);
        $validator = Validator::make($input,[
            'address_id' => 'required',
            'cart_id' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->responseFailed($validator->errors()->first());
        }
        $carts = json_decode($input['cart_id'],true);
        if(!is_array($carts) || empty($carts)) {
            return $this->responseFailed('购物车无商品提交');
        }
        foreach ($carts as $val) {
            $cart = Cart::find($val);
            if (!$cart) {
                return $this->responseFailed('购物车无此商品');
            }
            $sku = ProductSku::find($cart['product_sku_id']);
            if (!$sku) {
                return $this->responseFailed('商品不存在');
            }
            if ($sku['stock'] < $cart['amount']) {
                return $this->responseFailed('库存不足,请重新下单');
            }
        }
        $address = UserAddress::find($input['address_id']);
        if (!$address) {
            return $this->responseFailed('收货地址错误');
        }
        $pay_type = $request->pay_type;
        if(!in_array($pay_type, Order::PAY_TYPE)){
            return $this->responseFailed('支付方式错误');
        }
        try{
            $order = new Order();
            $order->contact_name = $address['contact_name'];
            $order->contact_phone = $address['contact_phone'];
            $order->address_detail = $address['full_address'];
            $order->user_id = $user['id'];
            $order->order_status = Order::ORDER_STATUS[0];
            $order->order_status_desc = Order::ORDER_STATUS_DESC[0];
            $order->pay_type = $pay_type;
            $order->pay_type_desc = Order::PAY_TYPE_DESC[$pay_type];
            $order->no = Order::findAvailableNo();
            $order->express_fee = Order::postfee($input['address_id'], $input['cart_id']);
            if (!empty($input['remark'])) {
                $order->remark = $input['remark'];
            }
            if (!$order->save()) {
                throw new Exception('保存失败');
            }
            OrderItem::AddItem($order, $input,$user);
            DB::commit();
            return $this->responseData($order->toArray());
        } catch (Exception $e) {
            DB::rollBack();
            return $this->responseFailed($e->getMessage());
        }
    }

    //取消订单
    public function close(Request $request)
    {
        if (!$request->id) {
            return $this->responseFailed('订单ID必传');
        }
        $order = Order::find($request->id);

        if (!$order) {
            return $this->responseFailed('订单不存在');
        }
        if ($order['is_closed'] == 1) {
            return $this->responseFailed('订单已经取消');
        }
        $order->is_closed = 1;
        DB::beginTransaction();
        if ($order->save()) {
            $item = OrderItem::where('order_id', $order['id'])->get();
            foreach ($item as $val) {
                $productSku = ProductSku::find($val['product_sku_id']);
                if ($productSku) {
                    $productSku->increment('stock', $val['amount']);
                }
            }
            DB::commit();
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }

    //订单列表
    public function index(Request $request)
    {
        $user = auth()->user();
        if (!$user) {
            return $this->responseFailed('token 过期');
        }
        $where = [
            ['is_closed', '=','0'],
            ['user_id', '=', $user['id']],
            ['is_pay', '!=','0'],
        ];
        $status = $request->input('status');
       /* if ($status == 1) {
            $where[] = ['is_pay', '=','0'];
        }*/
        if ($status == 1) {
            $where[] = ['is_pay', '=','1'];
            $where[] = ['is_send', '=','0'];
        }
        if ($status == 2) {
            $where[] = ['is_send', '=','1'];
            $where[] = ['is_receive', '=','0'];
        }
        if ($status == 3) {
            $where[] = ['is_send', '=','1'];
            $where[] = ['is_receive', '=','1'];
        }
        $orders = Order::where($where)
                ->orderBy('id', 'desc')
                ->paginate(10)
                ->toArray();
        foreach ($orders['data'] as &$val) {
            $val['order_status'] = Order::getOrderStaus($val);
            $val['order_item'] = OrderItem::getOrderItemByOrderId($val['id']);
        }
        return $this->responseData($orders);
    }

    //订单详情
    public function detail(Request $request)
    {
        if (!$request->id) {
            return $this->responseFailed('订单ID必传');
        }
        $order = Order::find($request->id);
        if (!$order) {
            return $this->responseFailed('查不到该订单');
        }
        if ($order['is_closed'] == 1) {
            return $this->responseFailed('订单已取消');
        }
        $order = $order->toArray();
        if (!empty($request->order_item_id)) {
            $orderItem = OrderItem::getItemById($request->order_item_id);
        } else {
            $orderItem = OrderItem::getOrderItemByOrderId($order['id']);
        }
        $order['order_item'] = $orderItem;
        return $this->responseData($order);
    }

    //确认收货
    public function receive(Request $request)
    {
        if (!$request->id) {
            return $this->responseFailed('订单ID必传');
        }
        $order = Order::find($request->id);
        if (!$order) {
            return $this->responseFailed('查不到该订单');
        }
        if ($order['is_closed'] == 1) {
            return $this->responseFailed('订单已取消');
        }
        if ($order['is_send'] != 1){
            return $this->responseFailed('订单没有发货');
        }
        $order->is_receive = 1;
        $order->order_status = Order::ORDER_STATUS[3];
        $order->order_status_desc =  Order::ORDER_STATUS_DESC[3];
        $order->receive_at = date('Y-m-d H:i:s');
        if(!$order->save()){
            return $this->responseFailed();
        }
        return $this->responseSuccess();
    }

    //发货提醒
    public function tip(Request $request)
    {
        if (!$request->id) {
            return $this->responseFailed('订单ID必传');
        }
        $user = auth()->user();
        $tip = OrderTip::where('order_id', $request->id)->first();
        if ($tip) {
            return $this->responseFailed('已经发送');
        }
        $tip = new OrderTip();
        $tip->order_id = $request->id;
        $tip->user_id = $user['id'];
        if ($tip->save()) {
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }

    //订单评价
    public function createReview(Request $request)
    {
        if (!$request->order_item_id) {
            return $this->responseFailed('订单order_item_id必传');
        }
        if (!$request->rating) {
            return $this->responseFailed('评分必传');
        }
        $user = auth()->user();
        $item = OrderItem::find($request->order_item_id);
        if (!$item) {
            return $this->responseFailed('无此订单');
        }
        if ($item['is_review'] == 1) {
            return $this->responseSuccess('该订单已评价');
        }
        $order = Order::find($item['order_id']);
        if ($order) {
            $order->reviewed = 1;
            $order->save();
        }
        $commnet = new ProductComment();
        $commnet->user_id = $user['id'];
        $commnet->product_id = $item['product_id'];
        $commnet->order_item_id = $request->order_item_id;
        $commnet->rating = $request->rating;
        if(!empty($request->review)){
            $commnet->commnet = $request->review;
        }
        $item->is_review = 1;
        if ($item->save() && $commnet->save()) {
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }

    //查看评价
    public function viewReview(Request $request)
    {
        if (!$request->order_item_id) {
            return $this->responseFailed('订单order_item_id必传');
        }
        $item = ProductComment::where('order_item_id', $request->order_item_id)->first();
        if (!$item) {
            return $this->responseFailed('无此订单');
        }
        $item = $item->toArray();
        $item['sku'] = OrderItem::getItemById($request->order_item_id);
        return $this->responseData($item);
    }

    public function refund(Request $request)
    {
        $input = $request->only([
            'order_id',
            'imgs',
            'reason',
        ]);
        $validator = Validator::make($input, [
            'order_id' => 'required',
            'imgs' => 'required',
            'reason' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->responseFailed($validator->errors()->first());
        }
        $refund = OrderRefund::getOneByOrderId($input['order_id']);
        if ($refund) {
            return $this->responseFailed('已经提交');
        }
        $user = auth()->user();
        $input['user_id'] = $user['id'];
        $model = new OrderRefund();
        foreach ($input as $key=>$val) {
            if (!empty($val)) {
                $model->$key = $val;
            }
        }
        if($model->save()){
            return $this->responseSuccess();
        }
        return $this->responseFailed();
    }
}